package com.matrix.framework.core.listcrud;


import com.matrix.framework.core.common.global.Pager;
import com.matrix.framework.core.common.utils.Common;
import com.matrix.framework.core.listcrud.data.BaseData;
import com.matrix.framework.core.listcrud.service.IListCrudService;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * List增删改查组件使用示例（多例模式）
 * 
 * 演示新的多例模式API的使用
 * 每个工厂实例维护独立的数据存储
 *
 * Copyright © 海平面工作室 版权所有
 *
 * @Author: Leo
 * @Create: 2025/9/20 11:00
 * @Since 1.2
 */
public class ListCrudExample {
    
    /**
     * 示例数据类
     */
    public static class User extends BaseData {
        private String name;
        private int age;
        private String email;
        
        public User() {
            super();
        }
        
        public User(String name, int age, String email) {
            super();
            this.name = name;
            this.age = age;
            this.email = email;
        }
        
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public int getAge() { return age; }
        public void setAge(int age) { this.age = age; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
        
        @Override
        public String toString() {
            return "User{id=" + getId() + ", name='" + name + "', age=" + age + ", email='" + email + "'}";
        }
    }
    
    /**
     * 主要使用示例 - 多例模式
     */
    public static void demonstrateUsage() {
        // 创建工厂实例
        ListCrudFactory factory = ListCrudFactory.create();
        
        // 通过工厂获取服务
        IListCrudService<User> userService = factory.getService(User.class);
        
        // 创建测试数据
        System.out.println("=== 创建测试数据 ===");
        userService.save(new User("张三", 25, "zhangsan@example.com"));
        userService.save(new User("李四", 30, "lisi@example.com"));
        userService.save(new User("王五", 28, "wangwu@example.com"));
        userService.save(new User("赵六", 22, "zhaoliu@example.com"));
        userService.save(new User("孙七", 35, "sunqi@example.com"));
        
        System.out.println("创建了 " + userService.count() + " 个用户");
        
        // 使用工厂直接操作数据
        System.out.println("\n=== 使用工厂直接操作数据 ===");
        User newUser = factory.save(User.class, new User("马八", 27, "maba@example.com"));
        System.out.println("通过工厂保存用户：" + newUser);
        
        System.out.println("当前总用户数：" + factory.count(User.class));
        
        // 新Pager API分页查询
        System.out.println("\n=== 分页查询 ===");
        Pager<User> pager = new Pager<>();
        pager.setPage(1);
        pager.setPageSize(2);
        
        Pager<User> result = factory.findAll(User.class, pager);
        System.out.println("分页结果：页码=" + result.getPage() + 
                          ", 页大小=" + result.getPageSize() + 
                          ", 总记录数=" + result.getTotal());
        System.out.println("当前页数据：");
        result.getItems().forEach(System.out::println);
        
        // 条件分页查询
        System.out.println("\n=== 条件分页查询 ===");
        Pager<User> conditionPager = new Pager<>();
        conditionPager.setPage(1);
        conditionPager.setPageSize(3);
        
        Pager<User> conditionResult = factory.findByCondition(
            User.class,
            user -> user.getAge() >= 25, 
            conditionPager
        );
        System.out.println("条件查询结果：年龄>=25的用户");
        System.out.println("总匹配记录数：" + conditionResult.getTotal());
        conditionResult.getItems().forEach(System.out::println);
    }
    
    /**
     * 多例模式演示 - 不同实例之间数据隔离
     */
    public static void demonstrateMultipleInstances() {
        System.out.println("\n=== 多例模式演示 - 数据隔离 ===");
        
        // 创建第一个工厂实例
        ListCrudFactory factory1 = ListCrudFactory.create();
        factory1.save(User.class, new User("实例1用户1", 25, "f1u1@test.com"));
        factory1.save(User.class, new User("实例1用户2", 30, "f1u2@test.com"));
        
        // 创建第二个工厂实例
        ListCrudFactory factory2 = ListCrudFactory.create();
        factory2.save(User.class, new User("实例2用户1", 28, "f2u1@test.com"));
        factory2.save(User.class, new User("实例2用户2", 32, "f2u2@test.com"));
        factory2.save(User.class, new User("实例2用户3", 26, "f2u3@test.com"));
        
        // 验证数据隔离
        System.out.println("工厂实例1的用户数量：" + factory1.count(User.class));
        System.out.println("工厂实例1的用户：");
        factory1.findAll(User.class).forEach(user -> System.out.println("  " + user));
        
        System.out.println("\n工厂实例2的用户数量：" + factory2.count(User.class));
        System.out.println("工厂实例2的用户：");
        factory2.findAll(User.class).forEach(user -> System.out.println("  " + user));
        
        System.out.println("\n演示：每个实例的数据完全独立！");
    }
    
    /**
     * 迁移指南演示
     */
    public static void demonstrateMigration() {
        System.out.println("\n=== API迁移指南 ===");
        
        System.out.println("旧方式 (静态方法，已移除):");
        System.out.println("ListCrudFactory.save(User.class, user);");
        System.out.println("ListCrudFactory.findAll(User.class);");
        
        System.out.println("\n新方式 (多例模式，推荐):");
        System.out.println("ListCrudFactory factory = ListCrudFactory.create();");
        System.out.println("factory.save(User.class, user);");
        System.out.println("factory.findAll(User.class);");
        
        System.out.println("\n服务方式 (仍然支持):");
        System.out.println("ListCrudFactory factory = ListCrudFactory.create();");
        System.out.println("IListCrudService<User> service = factory.getService(User.class);");
        System.out.println("service.save(user);");
        System.out.println("service.findAll();");
    }
    
    /**
     * 高级功能演示
     */
    public static void demonstrateAdvanced() {
        ListCrudFactory factory = ListCrudFactory.create();
        
        // 创建大量测试数据
        for (int i = 1; i <= 25; i++) {
            factory.save(User.class, new User("高级用户" + i, 18 + i % 20, "advanced" + i + "@test.com"));
        }
        
        System.out.println("\n=== 高级功能：分页遍历 ===");
        int pageSize = 5;
        int currentPage = 1;
        Pager<User> pageResult;
        
        do {
            Pager<User> queryPager = new Pager<>();
            queryPager.setPage(currentPage);
            queryPager.setPageSize(pageSize);
            
            pageResult = factory.findAll(User.class, queryPager);
            
            System.out.println("第 " + currentPage + " 页 (" + pageResult.getItems().size() + " 条记录):");
            pageResult.getItems().forEach(user ->
                System.out.println("  " + user.getName() + " (年龄:" + user.getAge() + ")"));
            
            currentPage++;
        } while (pageResult.getItems().size() == pageSize);
        
        System.out.println("总共遍历了 " + (currentPage - 1) + " 页");
    }
    
    /**
     * JSON数据导入导出演示
     */
    public static void demonstrateJsonImportExport() {
        System.out.println("\n=== JSON数据导入导出演示 ===");
        
        // 创建工厂实例
        ListCrudFactory factory = ListCrudFactory.create();
        
        // 创建初始测试数据
        factory.save(User.class, new User("原始用户1", 25, "original1@test.com"));
        factory.save(User.class, new User("原始用户2", 30, "original2@test.com"));
        factory.save(User.class, new User("原始用户3", 28, "original3@test.com"));
        
        System.out.println("1. 导出所有数据：");
        String exportedJson = factory.export(User.class);
        System.out.println("导出的JSON：" + exportedJson);
        
        System.out.println("\n2. 条件导出演示（年龄>=28的用户）：");
        String conditionalExport = factory.export(User.class, user -> user.getAge() >= 28);
        System.out.println("条件导出JSON：" + conditionalExport);
        
        // 准备新的JSON测试数据
        System.out.println("\n3. 加载新数据演示：");
        List<User> newUsers = Arrays.asList(
            new User("新用户1", 26, "new1@test.com"),
            new User("新用户2", 31, "new2@test.com"),
            new User("新用户3", 29, "new3@test.com")
        );
        
        String newJsonData = Common.listToJson(newUsers);
        System.out.println("新JSON数据：" + newJsonData);
        
        // 清空现有数据并加载新数据
        int loadedCount = factory.load(newJsonData, User.class, true);
        System.out.println("成功加载 " + loadedCount + " 条新数据");
        
        System.out.println("\n4. 验证加载结果：");
        System.out.println("当前总数据量：" + factory.count(User.class));
        factory.findAll(User.class).forEach(user -> System.out.println("  " + user));
        
        // 演示追加加载
        System.out.println("\n5. 追加加载演示：");
        List<User> additionalUsers = Arrays.asList(
            new User("追加用户1", 32, "add1@test.com"),
            new User("追加用户2", 24, "add2@test.com")
        );
        
        String additionalJsonData = Common.listToJson(additionalUsers);
        int additionalCount = factory.load(additionalJsonData, User.class, false);
        System.out.println("追加加载 " + additionalCount + " 条数据");
        System.out.println("最终总数据量：" + factory.count(User.class));
    }
    
    /**
     * 高级导出功能演示
     */
    public static void demonstrateAdvancedExport() {
        System.out.println("\n=== 高级导出功能演示 ===");
        
        ListCrudFactory factory = ListCrudFactory.create();
        
        // 创建测试数据
        for (int i = 1; i <= 10; i++) {
            factory.save(User.class, new User("测试用户" + i, 20 + i, "test" + i + "@example.com"));
        }
        
        System.out.println("1. 导出所有数据：");
        String allData = factory.export(User.class);
        System.out.println("所有数据JSON长度：" + allData.length());
        
        System.out.println("\n2. 根据年龄条件导出：");
        String youngUsers = factory.export(User.class, user -> user.getAge() < 25);
        System.out.println("年轻用户JSON：" + youngUsers);
        
        System.out.println("\n3. 根据ID列表导出：");
        List<Long> targetIds = Arrays.asList(1L, 3L, 5L, 7L);
        String selectedUsers = factory.exportByIds(User.class, targetIds);
        System.out.println("指定ID用户JSON：" + selectedUsers);
        
        System.out.println("\n4. 导出空数据演示：");
        String emptyResult = factory.export(User.class, user -> user.getAge() > 100);
        System.out.println("空结果JSON：" + emptyResult);
    }
    
    /**
     * 全面功能演示
     */
    public static void demonstrateComprehensive() {
        System.out.println("\n=== 全面功能演示 ===");
        
        ListCrudFactory factory = ListCrudFactory.create();
        
        // 1. 批量保存
        List<User> users = Arrays.asList(
            new User("张三", 25, "zhangsan@test.com"),
            new User("李四", 30, "lisi@test.com"),
            new User("王五", 28, "wangwu@test.com"),
            new User("赵六", 22, "zhaoliu@test.com")
        );
        List<User> savedUsers = factory.saveAll(User.class, users);
        System.out.println("批量保存了 " + savedUsers.size() + " 个用户");
        
        // 2. 查询操作
        System.out.println("\n查询操作：");
        Optional<User> firstUser = factory.findById(User.class, 1L);
        System.out.println("ID为1的用户：" + firstUser.orElse(null));
        
        List<User> adultUsers = factory.findByCondition(User.class, user -> user.getAge() >= 25);
        System.out.println("成年用户数量：" + adultUsers.size());
        
        Optional<User> firstAdult = factory.findFirstByCondition(User.class, user -> user.getAge() >= 25);
        System.out.println("第一个成年用户：" + firstAdult.orElse(null));
        
        // 3. 统计操作
        System.out.println("\n统计操作：");
        long totalCount = factory.count(User.class);
        long adultCount = factory.countByCondition(User.class, user -> user.getAge() >= 25);
        System.out.println("总用户数：" + totalCount + "，成年用户数：" + adultCount);
        
        // 4. 存在性检查
        boolean exists = factory.existsById(User.class, 1L);
        boolean hasElder = factory.existsByCondition(User.class, user -> user.getAge() > 50);
        System.out.println("ID=1存在：" + exists + "，有老年用户：" + hasElder);
        
        // 5. 删除操作
        System.out.println("\n删除操作：");
        boolean deleted = factory.deleteById(User.class, 1L);
        System.out.println("删除ID=1结果：" + deleted);
        
        int deletedCount = factory.deleteByCondition(User.class, user -> user.getAge() < 25);
        System.out.println("删除年轻用户数量：" + deletedCount);
        
        System.out.println("删除后剩余用户数：" + factory.count(User.class));
    }
    
    /**
     * 运行所有演示
     */
    public static void runAllDemos() {
        System.out.println("===== List增删改查组件演示（多例模式） =====");
        
        demonstrateUsage();
        demonstrateMultipleInstances();
        demonstrateMigration();
        demonstrateAdvanced();
        demonstrateJsonImportExport();
        demonstrateAdvancedExport();
        demonstrateComprehensive();
        
        System.out.println("\n===== 演示完成 =====");
    }
    
    /**
     * 主方法 - 运行演示
     */
    public static void main(String[] args) {
        runAllDemos();
    }
} 